/**
 * Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.
 */

!time limit exceeded

package com.xinpan.exercise;


public class DecodeWays {
    public int numDecodings(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(s.length() == 0)
            return 0;
        else if(s.length() == 1 && s.charAt(0) != '0')
            return 1;
        else if(s.length() == 1)
            return 0;
            
        
        int pos = 0;
        int sum = 0;
        int n1 = Integer.valueOf(s.substring(pos, pos+1));
        
        if(n1 >= 1 && n1 <= 9)
            sum += decNum(pos+1, s);
        
        if(n1 >=1 && n1 <=2)
        {
            int n2 = Integer.valueOf(s.substring(pos+1, pos+2));
            if(n2 >= 0 && n2 <= 6)
                sum += decNum(pos+2, s);
        }
        
        
        return sum;
    }
    
    public int decNum(int pos, String s)
    {
        if(pos == s.length())
            return 1;
        else if(s.charAt(pos) == '0')
            return 0;
        else if(pos == s.length()-1)
            return 1;
        
    
        int sum = 0;
        int n1 = Integer.valueOf(s.substring(pos, pos+1));
        if(n1 >= 1 && n1 <= 9)
            sum += decNum(pos+1, s);
        
        if(n1 >=1 && n1 <=2)
        {
            int n2 = Integer.valueOf(s.substring(pos+1, pos+2));
            if(n2 >= 0 && n2 <=6)
                sum += decNum(pos+2, s);
        }
        
        return sum;
    }
    
    public static void main(String[] args)
    {
    	DecodeWays dw = new DecodeWays();
    	dw.numDecodings("100");
    }
}
